package cn.itcast.service.impl;

import cn.itcast.dao.PermissionDao;
import cn.itcast.entity.PageResult;
import cn.itcast.pojo.Permission;
import cn.itcast.service.PermissionService;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionDao permissionDao;



    //查询所有权限信息
    @Override
    public List<Permission> findAll() {

        return permissionDao.findAll();
    }


    //分页查询
    @Override
    public PageResult pageQuery(Integer currentPage, Integer pageSize, String queryString) {
        log.info("------PermissionServiceImpl------pageQuery------传递到实现类的分页参数------当前"+currentPage+"页,"+"每页展示"+pageSize+"条,"+"查询条件为:"+queryString);
        PageHelper.startPage(currentPage, pageSize);
        Page<Permission> page = permissionDao.findByCondition(queryString);
        log.info("------PermissionServiceImpl------pageQuery------查询到的分页对象信息page------"+page);
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public Permission findById(Integer id) {
        return permissionDao.findById(id);
    }


    //新增权限
    @Transactional
    @Override
    public void add(Permission permission) {
        permissionDao.add(permission);
    }

    @Transactional
    @Override
    public void deleteById(Integer id) {
        //判断该权限是否被引用
        int countMenu = permissionDao.selectMenuReferencedCount(id);
        log.info("------PermissionServiceImpl------deleteById------权限被菜单引用的次数------"+countMenu);
        int countRole = permissionDao.selectRoleReferencedCount(id);
        log.info("------PermissionServiceImpl------deleteById------权限被角色引用的次数------"+countRole);
        if(countMenu>0||countRole>0){
            throw new RuntimeException("当前权限被引用，不能删除 !");
        }

        //删除权限
        permissionDao.deleteById(id);
    }

    //更新权限信息
    @Transactional
    @Override
    public void update(Permission permission) {
        permissionDao.update(permission);
    }





}
